/* 自动业务页面配置 */

const fs = require('fs');
const glob = require('glob');
const babel = require("@babel/core");
const types = require('@babel/types');
const template = require('@babel/template');
const { hyphen } = require('naming-style');

function PageDog(options) {
  this.options = options;
}
module.exports = PageDog;

PageDog.prototype.apply = function (compiler) {
  compiler.hooks.environment.tap('a', () => {
    this.generate();
  });
};

PageDog.prototype.generate = function() {
  function pageProperty(path, filePath) {
    return types.objectProperty(
      types.stringLiteral(`/${path}`),
      template.expression(`() => import(COMPONENT_FILE_PATH)`, {
        plugins: ['dynamicImport']
      })({
        COMPONENT_FILE_PATH: types.stringLiteral(`@/pages/${filePath}`)
      })
    );
  }

  /*
  构造：
  export deafult {
    组件1 path: () => import(组件文件路径),
    组件2
    组件N
    ...
  }
  */
  let pageProperties = [];
  let pageCount = 0;
  // 遍历pages中每个**Page.vue/js
  glob.sync('./src/pages/**/**Page.+(js|vue)').forEach((filename) => {
    // 组件文件路径
    let filePath = /\.\/src\/pages\/(.*?).(js|vue)/.exec(filename)[1];
    
    // path
    const nameIndex = filePath.lastIndexOf('/');
    let name = filePath.substring(nameIndex + 1);
    name = hyphen(name.substring(0, name.length - 4)).toLowerCase();
    let path = filePath.substring(0, nameIndex + 1) + name;

    // 如 /details/index 这样的路径，使用：/details
    if (path.endsWith('/index')) {
      path = path.substring(0, path.length - '/index'.length);
    }
    pageProperties.push(pageProperty(path, filePath));
    pageCount++;
  });

  let program = types.program([
    types.exportDefaultDeclaration(
      types.objectExpression(pageProperties)),
  ]);

  let outSrcPath = `src/${this.options.dir}/pages.js`;
  fs.writeFileSync(outSrcPath, babel.transformFromAstSync(program).code);
  console.log(`成功生成 ${outSrcPath}, 共 ${pageCount} 个页面.`);
}